package com.zheng.hr.rpc.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zheng.common.annotation.BaseService;

import com.zheng.hr.dao.model.HrDict;
import com.zheng.hr.dao.model.HrPaidLeave;
import com.zheng.hr.dao.mapper.HrPaidLeaveMapper;
import com.zheng.hr.rpc.api.HrDictService;
import com.zheng.hr.rpc.api.HrPaidLeaveService;
import com.zheng.common.base.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 休假表 服务实现类
 * </p>
 *
 * @author likun
 * @since 2018-05-03
 */
@Service
@Transactional
@BaseService
public class HrPaidLeaveServiceImpl extends BaseServiceImpl<HrPaidLeaveMapper, HrPaidLeave> implements HrPaidLeaveService {
    @Autowired
    private HrDictService dictService;
    private static final Integer WORK_HALF_DAY_HOURS = 7;

    public boolean insertOverTimePaidLeave(Double day, Integer hours, String username) {
        String offValue = dictService.getDictValue("调休假", "leave_type", "0");

        HrPaidLeave paidLeave;
        EntityWrapper<HrPaidLeave> paidLeaveEntityWrapper = new EntityWrapper<>();
        paidLeaveEntityWrapper.eq("type", offValue).eq("username", username);
        paidLeave = selectOne(paidLeaveEntityWrapper);
        if (null == paidLeave) {
            paidLeave = new HrPaidLeave();
            paidLeave.setType(Integer.parseInt(offValue));
            paidLeave.setUsername(username);
            paidLeave.setLeftHours(0);
            paidLeave.setUsedDays(0D);
            paidLeave.setDays(0D);
        }
        //获取之前已设置的时间信息
        Integer oldLeftHours = paidLeave.getLeftHours();
        Double oldDays = paidLeave.getDays();

        //设置小时数*2 为了防止操作小数
        Integer doubleHours = hours * 2 + oldLeftHours;
        //根据总小时
        Integer leftHours = doubleHours % WORK_HALF_DAY_HOURS;
        //小时数如果超过一天，就折合天数
        //小时数*2 / 半天的小时 = 增加的天数
        Integer addHalfDay = doubleHours / WORK_HALF_DAY_HOURS;
        Double addDay = addHalfDay / 2d + day + oldDays;
        paidLeave.setLeftHours(leftHours);
        paidLeave.setDays(addDay);
        if(paidLeave.getId() != null){
            return updateById(paidLeave);
        }
        return insert(paidLeave);
    }
}
